var common = require("../../utils/public.js")
var api = require("../../utils/api.js")
Page({

  /**
   * 页面的初始数据
   */
  data: {
    toBack: false,
    indexs: '',
    timer: '',
    start: 0,
    end: 0,
    shopBack: [],
    codeNum: "",
    userMessage: '',
    //城市
    city: '',
    //微信头像
    avatarUrl: '',
    //省份
    province: '',
    //性别
    gender: '',
    //微信名字
    nickName: '',
    storeChoose: '',
    codeNum: '',
    tokenCode: '',
    carts: [], //购物车列表
    selectAllStatus: true, //全选状态
    // 金额
    totalPrice: 0, // 商品总价，初始为0（活动优惠后金额）
    hasList: true,
    setting: [],
    goodsRecommend: [],
    //运费
    minAmount: 0,
    //最大运费
    maxAmount: 0,
    //起送金额
    minAmountPrice: 0,
    //再买多少钱免运费
    // reduction:"",
    //总押金
    totalDeposit: 0,
    //金币
    jb: 0,
    qsPrice: 0,
    startX: 0, //开始坐标
    startY: 0,
    isInit: false,
    shopOrMan: -1,
    size: 1000,
    //数量
    inputNum: '',
    //购物车原有数量
    inputNum1: '',
    goodsName: '',
    goodsDetailsId: '',
    price: '',
    totalPrice: '',
    //起送数量
    detailStartNum: '',
    //活动数组
    activityList: [],
    //所有数据
    list: [],

    // 金额合计 totalDeposit + totalPrice
    summationPrice: 0
  },

  //手指触摸动作开始 记录起点X坐标
  touchstart: function (e) {
    var that = this;
    //开始触摸时 重置所有删除
    that.data.list.forEach(function (v, i) {
      if (v.isTouchMove) //只操作为true的
        v.isTouchMove = false
    })
    that.setData({
      startX: e.changedTouches[0].clientX,
      startY: e.changedTouches[0].clientY,
      list: that.data.list
    })
  },
  //滑动事件处理
  touchmove: function (e) {
    const {
      list
    } = this.data
    var that = this,
      id = e.currentTarget.dataset.id, //当前索引

      startX = that.data.startX, //开始X坐标
      startY = that.data.startY, //开始Y坐标
      touchMoveX = e.changedTouches[0].clientX, //滑动变化坐标
      touchMoveY = e.changedTouches[0].clientY, //滑动变化坐标
      angle = that.angle({
        X: startX,
        Y: startY
      }, {
        X: touchMoveX,
        Y: touchMoveY
      }); //获取滑动角度

    list.forEach(function (v, i) {
      v.isTouchMove = false
      //滑动超过30度角 return
      if (Math.abs(angle) > 30) return;
      if (v.id == id) {
        if (touchMoveX > startX) //右滑
          v.isTouchMove = false
        else //左滑
          v.isTouchMove = true
      }
    })


    // 分活动
    let {
      activity,
      activityList
    } = this.data
    let goods = this.goodsListToMap(list)
    goods = this.calculateGoodsInfo(goods, activity)
    this.setData({
      list,
      goods,
      activity,
      activityList
    })

  },
  // 计算滑动角度
  angle: function (start, end) {
    var _X = end.X - start.X,
      _Y = end.Y - start.Y;
    //返回角度 /Math.atan()返回数字的反正切值
    return 360 * Math.atan(_Y / _X) / (2 * Math.PI);
  },

  onLoad: function (options) {

  },
  getShopSum() {
    api.get_cart({
        cityId: wx.getStorageSync("cityId"),
        userId: wx.getStorageSync("openId"),
        page: {
          size: this.data.size
        }
      })
      .then(res => {
        let getSum = res.data.body.getSum;
        const {goodsRecommend} = res.data.body

        if (wx.getStorageSync('type') == "2") {
          goodsRecommend.forEach(v => {
            v.detailSalesPrice = v.detailPersonalPrice || 0
            v.detailSalesPriceVip = v.detailPersonalPriceVip || 0
          })
        }
     
        if (getSum > 0) {
          wx.setTabBarBadge({
            index: 3,
            text: getSum + '' //显示的内容 
          })
        } else {
          wx.hideTabBarRedDot({
            index: 3
          })
        }
      })
  },

  onShow: function () {
    let that = this
    if (wx.getStorageSync('codeNum') == 104) {
      //组件接口
      api.shopBack({
          cityId: wx.getStorageSync("cityId")
        })
        .then(res => {
          if (res.result && res.body.getShopInfo.length) {
            console.log(res)
            let len = res.body.getShopInfo.length - 1;
            let shopBack = res.body.getShopInfo[len]

            this.setData({
              shopBack,
              codeNum: wx.getStorageSync("codeNum")
            })
          }
        })
    }
    if (wx.getStorageSync('codeNum') == 99) {
      that.getShopSum()
      that.uploadGoodsRecommend()
    }
    that.setData({
      codeNum: wx.getStorageSync('codeNum'),
      tokenCode: wx.getStorageSync('token'),
      userMessage: wx.getStorageSync('userMessage'),
      shopOrMan: wx.getStorageSync("type")
    })
    that.setData({
      city: that.data.city,
      avatarUrl: that.data.avatarUrl,
      province: that.data.province,
      gender: that.data.gender,
      nickName: that.data.nickName,
    })
    api.shopType({}).then(res => {
      if (res.result) {
        this.setData({

          storeChoose: res.object,
        })
      }
    })
    that.setData({
      toBack: true
    })
  },


  calculateActivityInfo(list) {
    let activity = {
      0: []
    }
    let activityNameMap = {}
    // 分出活动对应的商品
    list.forEach(i => {
      if (i.activityFullReduceId && !activity[i.activityFullReduceId]) {
        activity[i.activityFullReduceId] = i.activityFullReduceLadderEntityList
        activityNameMap[i.activityFullReduceId] = {
          name: i.activityFullReduceName || '',
          activityFullReduceUseTicket: i.activityFullReduceUseTicket,
          activityFullReduceBeginDate: i.activityFullReduceBeginDate,
          activityFullReduceEndDate: i.activityFullReduceEndDate
        }
      }
    })
    this.setData({
      activityNameMap
    })
    Object.keys(activity).forEach(i => {
      if (i != '0') {
        activity[i] = activity[i].sort((a, b) => a.fullAmount - b.fullAmount)
      }
    })

    // 分出活动
    let activityList = []
    Object.keys(activity).forEach((i, index) => {
      activityList[index] = {}
      activityList[index].activityFullReduceId = i
      // activityList[index].activityName = activityNameMap[i].name || ''
      activityList[index].rule = activity[i]
    })
    return {
      activity,
      activityList: activityList.reverse()
    }
  },

  goodsListToMap(list) {
    let goods = {
      0: {
        list: []
      }
    }
    // 分出活动对应的商品
    list.forEach(i => {
      if (i.activityFullReduceId) {
        if (goods[i.activityFullReduceId]) {
          goods[i.activityFullReduceId].list.push(i)

        } else {
          goods[i.activityFullReduceId] = {}
          goods[i.activityFullReduceId].list = [i]
        }
      } else {
        goods[0].list.push(i)
      }
    })
    return goods
  },
  calculateGoodsInfo(goods, activity) {
    // 计算活动下商品总价
    Object.keys(goods).forEach(i => {
      let total = 0
      if (goods[i].list.length) {
        goods[i].list.forEach(it => {
          if (it.flag == '1') {
            total += +it.priceToShow * it.amount
          }
        })
      }
      goods[i].total = total
    })

    Object.keys(goods).forEach(i => {
      // i 为0 说明没参加活动
      if (i != '0') {
        const rules = activity[i]
        let maxFullAmount = rules[rules.length - 1].fullAmount

        if (goods[i].total >= maxFullAmount) {
          goods[i].maxFullAmount = true
        }
        let shouReduce = 0
        let disfullAmount = 0
        let mayReduce = 0
        let fullAmount = 0


        for (let it = 0; it < rules.length; it++) {
          const a = rules[it]

          if (goods[i].total >= a.fullAmount) {
            shouReduce = a.reduceAmount

            // 满足的应减
            goods[i].shouReduce = shouReduce
            // 满足的满减上限
            goods[i].shouFullAmount = a.fullAmount
            // 距离下个阶梯差值金额
            goods[i].disfullAmount = disfullAmount
            // 下一阶梯应减金额
            goods[i].mayReduce = mayReduce
            // 下一阶梯满减上限
            goods[i].fullAmount = fullAmount
            // 该活动下商品应付金额
            goods[i].shouldPay = goods[i].total - shouReduce
            // 该活动满足的满减阶梯规则
            goods[i].fulfil = a

          } else if (goods[i].total < a.fullAmount) {
            disfullAmount = a.fullAmount - goods[i].total
            mayReduce = a.reduceAmount
            fullAmount = a.fullAmount

            goods[i].shouReduce = shouReduce
            goods[i].disfullAmount = disfullAmount
            goods[i].mayReduce = mayReduce
            goods[i].fullAmount = fullAmount
            goods[i].shouldPay = goods[i].total - shouReduce
            break
          }
        }
      } else {
        goods[i].shouReduce = 0
        goods[i].disfullAmount = 0
        goods[i].mayReduce = 0
        goods[i].fullAmount = 0
        goods[i].shouldPay = goods[i].total
      }
    })

    let totalPrice = 0
    Object.keys(goods).forEach(i => {
      totalPrice += +goods[i].shouldPay
    })
    this.setData({
      totalPrice: totalPrice.toFixed(2)
    })
    return goods
  },
  // 组件中数据刷新
  uploadGoodsRecommend: function () {
    let that = this
    let cityId = wx.getStorageSync("cityId")
    let userId = wx.getStorageSync("openId")
    // TODO 获取userId/cityId
    userId = wx.getStorageSync("openId")
    cityId = wx.getStorageSync("cityId")
    api.get_cart({
      cityId,
      userId,
      page: {
        size: that.data.size
      }
    }).then(res => {
      let data = res.data.body
      //满减列表
      // let fullDecrementList = data.shopCar.records[0].activityFullReduceLadderEntityList
      //购物车列表
      let carts = data.shopCar.records;

      const {
        vipFlag
      } = res.data.object

      carts.forEach((good) => {
        let priceToShow = 0
        //  let priceToThrough = 0
        if (good.seckillPrice) { // 秒杀
          priceToShow = good.seckillPrice || 0
        } else if (good.rookiePrice && data.isNewcomer) { // 新人
          priceToShow = good.rookiePrice || 0
        } else if (vipFlag == 1) { // vip
          // 个人vip
          if (wx.getStorageSync('type') == "2") {
            priceToShow = good.detailPersonalPriceVip || 0
          } else {// 店铺vip
            priceToShow = good.detailSalesPriceVip || 0
          }
        } else { // 原价
          if (wx.getStorageSync('type') == "2") {
            priceToShow = good.detailPersonalPrice || 0
          } else {
            priceToShow = good.detailSalesPrice || 0
          }
        }
        good.priceToShow = priceToShow
      })

      // 分活动
      let {
        activity,
        activityList
      } = this.calculateActivityInfo(carts)
      let goods = this.goodsListToMap(carts)
      goods = this.calculateGoodsInfo(goods, activity)
      this.setData({
        goods,
        activity,
        activityList
      })

      wx.setStorageSync("userMess", res.data.object)
      that.setData({
        jb: res.data.object.balance,
      })
      for (var i = 0; i < data.settingBase.length; i++) {
        //起送金额
        if (data.settingBase[i].type == 1) {
          that.setData({
            minAmountPrice: data.settingBase[i].minAmount.toFixed(2),
          })
          //运费
        } else if (data.settingBase[i].type == 2) {
          const it = data.settingBase[i]
          that.setData({
            // 基础运费
            minAmount: it.minAmount.toFixed(2),
            maxAmount: it.maxAmount.toFixed(2),
            // 基础件数
            minNumber: it.minNumber,
            // 每超出基础件数
            overNumber: it.overNumber,
            // 每超出件数的运费
            overAmount: it.overAmount,
          })
        }
      }
      let setting = data.settingBase
      let goodsRecommend = data.goodsRecommend
      if (wx.getStorageSync('type') == "2") {
        goodsRecommend.forEach(v => {
          v.detailSalesPrice = v.detailPersonalPrice || 0
          v.detailSalesPriceVip = v.detailPersonalPriceVip || 0
        })
      }
      // 获取组件
      let recomment = this.selectComponent("#recomment")
      recomment.setGoodsRecommend(goodsRecommend)

      that.setData({
        isInit: true,
        list: carts,
        goodsRecommend,
        setting
      });
      that.countPrice()
      that.selectLists()
    })
  },


  mytouchstart: function (e) { //记录触屏开始时间
    this.setData({
      start: e.timeStamp
    })
  },
  mytouchend: function (e) { //记录触屏结束时间
    let that = this
    this.setData({
      end: e.timeStamp
    })
    if (that.data.end - that.data.start < 350) {
      that.addCount(e)
    }
    clearInterval(that.data.timer);
  },
  deleteitem: function (e) {
    let that = this
    let timer = setInterval(function () { //定义定时器
      that.addCount(e)
    }, 200);
    that.setData({
      timer: timer
    })
  },

  //添加数量
  addCount: function (e) {
    let that = this
    // 获取点击的id
    const item = e.currentTarget.dataset.item;

    // 获取商品数据
    let list = that.data.list;
    // 获取商品数量
    // let index = carts.findIndex(item => item.id === id)
    // // 点击递增
    // 计算金额方法
    let totalPrice = that.countPrice();
    // 访问接口更新数据
    // TODO 获取userId/cityId
    let userInfoId = wx.getStorageSync("openId")
    let cityId = wx.getStorageSync("cityId")
    let goodsName = item.goodsName
    let goodsDetailsId = item.goodsDetailsId
    let price = item.detailPrice
    let itemaa = list.filter(i => {
      return i.id == item.id
    })[0]
    let amount = +itemaa.amount + 1

    api.set_amount({
      cityId,
      userInfoId,
      goodsName,
      goodsDetailsId,
      amount,
      price,
      totalPrice
    }).then(res => {
      if (res.result) {
        if (res.data > 0) {
          wx.setTabBarBadge({
            index: 3,
            text: res.data //显示的内容 
          })
        }
        this.uploadGoodsRecommend()

        // 重新渲染 ---显示新的数量

        list.forEach(i => {
          if (i.id == item.id) {
            i.amount = +i.amount + 1
          }
        })
        // 分活动
        let {
          activity,
          activityList
        } = this.calculateActivityInfo(that.data.list)
        let goods = this.goodsListToMap(that.data.list)
        goods = this.calculateGoodsInfo(goods, activity)
        this.setData({
          list,
          goods,
          activity,
          activityList
        })


      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })

  },

  //减少数量
  btnMinus: function (e) {

    let that = this
    //  获取点击的索引id
    const item = e.currentTarget.dataset.item;
    //最少起送数量
    const detailStartNum = item.detailStartNum;

    // 获取商品数据
    let list = that.data.list;
    let itemaa = list.filter(i => {
      return i.id == item.id
    })[0]
    let amount = detailStartNum == item.amount ? 0 : +itemaa.amount - 1

    // 计算金额方法
    let totalPrice = that.countPrice();
    // 访问接口更新数据
    // TODO 获取userId/cityId
    let userInfoId = wx.getStorageSync("openId")
    let cityId = wx.getStorageSync("cityId")
    let goodsName = item.goodsName
    let goodsDetailsId = item.goodsDetailsId
    let price = item.detailPrice
    api.set_amount({
      cityId,
      userInfoId,
      goodsName,
      goodsDetailsId,
      amount,
      price,
      totalPrice
    }).then(res => {

      if (res.result) {
        if (res.data > 0) {
          wx.setTabBarBadge({
            index: 3,
            text: res.data //显示的内容 
          })
        } else {
          wx.hideTabBarRedDot({
            index: 3
          })
        }
        this.uploadGoodsRecommend()


        list.forEach(i => {
          if (i.id == item.id) {
            i.amount = +i.amount - 1
          }
        })
        // 分活动
        let {
          activity,
          activityList
        } = this.calculateActivityInfo(that.data.list)
        let goods = this.goodsListToMap(that.data.list)
        goods = this.calculateGoodsInfo(goods, activity)
        this.setData({
          list,
          goods,
          activity,
          activityList
        })
      } else {
        wx.showToast({
          title: res.msg,
          icon: 'none'
        })
      }
    })
  },

  //计算金额方法
  countPrice: function () {

    let that = this
    // 获取商品列表数据
    let list = that.data.list;
    // 声明一个变量接收数组列表detailPrice
    let total = 0;
    // 声明一个变量接收数组列表押金
    let deposit = 0;
    // 循环列表得到每个数据

    for (let i = 0; i < list.length; i++) {
      // 判断选中计算价格
      if (list[i].flag == 1) {
        // 所有价格加起来 count_money
        // total += list[i].amount * list[i].detailSalesPrice;

        deposit += list[i].amount * list[i].detailDeposit;
      }
    }

    const goods = that.data.goods
    let totalPrice = 0
    let reduce = 0
    Object.keys(goods).forEach(i => {
      totalPrice += +goods[i].shouldPay
      reduce += +goods[i].shouReduce
    })

    that.setData({
      totalPrice: totalPrice.toFixed(2),
      reduce: reduce.toFixed(2),
      totalDeposit: deposit.toFixed(2),
      summationPrice: (+totalPrice + +deposit).toFixed(2)
    })
    that.qsPrice()
    return total.toFixed(2)
  },

  //单商品点击事件
  selectList(e) {
    var that = this;
    var id = e.currentTarget.dataset.id
    //获取数组
    const list = that.data.list
    let flag = ''
    list.forEach(i => {
      if (i.id == id) {
        i.flag = i.flag == 1 ? 0 : 1
        flag = i.flag
      }
    })
    // 分活动
    let {
      activity,
      activityList
    } = this.calculateActivityInfo(that.data.list)
    let goods = this.goodsListToMap(that.data.list)
    goods = this.calculateGoodsInfo(goods, activity)
    this.setData({
      list,
      goods,
      activity,
      activityList
    })

    api.editFlag({
      flag: flag,
      id: e.currentTarget.dataset.id,
      cityId: '',
    }).then(res => {
      if (res.result == true) {
        that.selectLists()
        that.qsPrice()
      }

      //调用计算金额方法
      that.countPrice();
      //计算还有多少钱免运费
      //  that.reduction();
    })
  },



  //计算全选状态
  selectLists() {
    const {
      list
    } = this.data
    const selectAllStatus = list.every(i => i.flag == 1)
    this.setData({
      selectAllStatus
    })
  },

  /**
   * 购物车全选事件
   */
  selectAll(e) {

    let that = this;
    // 全选ICON默认选中
    let selectAllStatus = that.data.selectAllStatus;
    var flag = ""
    if (selectAllStatus == true) {
      flag = 0
    } else {
      flag = 1
    }
    selectAllStatus = !selectAllStatus;
    // 获取商品数据
    let list = that.data.list;
    for (let i = 0; i < list.length; i++) {
      list[i].flag = selectAllStatus;
    }

    api.editFlag({
      userInfoId: wx.getStorageSync("openId"),
      cityId: wx.getStorageSync("cityId"),
      flag: flag
    }).then(res => {
      if (res.result == true) {

        list.forEach(i => {
          i.flag = flag
        })
        // 分活动
        let {
          activity,
          activityList
        } = this.calculateActivityInfo(that.data.list)
        let goods = this.goodsListToMap(that.data.list)
        goods = this.calculateGoodsInfo(goods, activity)
        this.setData({
          list,
          goods,
          activity,
          activityList
        })

        that.setData({
          selectAllStatus: selectAllStatus,
        });



        // 计算金额方法
        that.countPrice();
        that.qsPrice()
        // that.reduction();
      }

    })
  },

  calYunFei(buyCarts, minAmount, minNumber, overNumber, overAmount) {
    const n = buyCarts.reduce((acc, good) => {
      return acc + Number(good.amount)
    },0)
    if(n <= minNumber) {
      return Number(minAmount)
    }
    const r = Math.ceil((n -  minNumber) / Number(overNumber)) * Number(overAmount) + Number(minAmount)
    return r
  },

  //去结算
  settlement: common.throttleFunc(function (e) {
    const {minNumber, overNumber, overAmount} = this.data

    const type = wx.getStorageSync('type')
    if (type==0) {
      const authFunction = wx.getStorageSync('authFunction')
      const index = authFunction.indexOf("0")
      if(index == -1) {
        wx.showToast({
          title: '暂无权限',
          icon: "none"
        })
        return
      } 
    }
    let that = this
    let buyCarts = []
    // 获取选择的商品
    let carts = this.data.list

    carts.forEach(function (v) {
      if (v.flag == 1) {
        buyCarts.push(v)
      }
    });

    // 获取总价未满减前的总价

    let totalPrice = that.data.totalPrice
    // const totalPrice = buyCarts.reduce((acc, it) => acc + it.priceToShow * it.amount, 0)
    // console.log(totalPrice, 'totalPrice');

    // 获取最低起送金额
    let setting = that.data.setting
    //判断是否添加运费
    let minAmount = ""
    //总押金
    let totalDeposit = that.data.totalDeposit
    //京币
    let jb = that.data.jb

    if (Number(that.data.totalPrice) >= Number(that.data.maxAmount)) {
      minAmount = 0.00

    } else {
      minAmount = this.calYunFei(buyCarts, this.data.minAmount, minNumber, overNumber, overAmount)
      console.log(minAmount);
    }

    let {
      activity
    } = this.calculateActivityInfo(buyCarts)
    let goods = this.goodsListToMap(buyCarts)
    goods = this.calculateGoodsInfo(goods, activity)
    const ac = Object.keys(goods).filter(i => i != '0')

    const {
      activityNameMap
    } = this.data
    let rules = []
    ac.forEach(i => {
      if (goods[i].fulfil) {
        rules.push({
          ...goods[i].fulfil,
          activityFullReduceName: activityNameMap[i].name,
          activityFullReduceUseTicket: activityNameMap[i].activityFullReduceUseTicket,
          activityFullReduceEndDate: activityNameMap[i].activityFullReduceEndDate,
          activityFullReduceBeginDate: activityNameMap[i].activityFullReduceBeginDate,
        })
      }
    })

    // 判断是否购买了商品
    if (buyCarts.length > 0) {
      // 判断是否超过起送价格
      if (Number(totalPrice) >= Number(that.data.minAmountPrice)) {
        wx.navigateTo({
          url: "/pages/pay/pay?carts=" + encodeURIComponent(JSON.stringify({
            buyCarts,
            totalPrice,
            setting,
            minAmount,
            totalDeposit,
            jb,
            rules
          }))
        })
      } else {
        wx.showToast({
          title: '未达到最低消费，无法配送',
          icon: 'none',
          duration: 1500
        })
      }
    } else {
      wx.showToast({
        title: '请选择商品',
        icon: 'none',
        duration: 1500
      })
    }
  }),

  //去详情
  details: function (e) {
    wx.navigateTo({
      url: '../detail/detail?id=' + e.currentTarget.dataset.id + '&shopid=' + e.currentTarget.dataset.shopid,
    })
  },

  //起送金额
  qsPrice: function (e) {
    let that = this
    let totalPrice = that.data.totalPrice
    let minAmountPrice = that.data.minAmountPrice
    let qsPrice = that.data.qsPrice
    if (Number(totalPrice) >= Number(minAmountPrice)) {
      that.setData({
        qsPrice: -1
      })
    } else {
      that.setData({
        qsPrice: Number(minAmountPrice - totalPrice).toFixed(2)
      })
    }
  },

  //删除
  remove: function (e) {

    let that = this
    //  获取点击的索引id
    const item = e.currentTarget.dataset.t1;
    const id = item.id;
    // 获取商品数据
    let list = that.data.list;
    let index = list.findIndex(item => item.id === id)
    // 计算金额方法
    let totalPrice = that.countPrice();
    // 访问接口更新数据
    // TODO 获取userId/cityId
    let userInfoId = wx.getStorageSync("openId")
    let cityId = wx.getStorageSync("cityId")
    let goodsName = item.goodsName
    let goodsDetailsId = item.goodsDetailsId
    let price = item.detailPrice
    let amount = 0;
    wx.showModal({

      content: '确定要删除此商品吗？',
      cancelText: '取消',
      confirmText: '删除',
      success(res) {
        if (res.cancel) {

        } else if (res.confirm) {
          api.set_amount({
            cityId,
            userInfoId,
            goodsName,
            goodsDetailsId,
            amount,
            price,
            totalPrice
          }).then(res => {
            // this.reduction()
            that.uploadGoodsRecommend()
            if (res.data > 0) {
              wx.setTabBarBadge({
                index: 3,
                text: res.data //显示的内容 
              })
            } else {
              wx.hideTabBarRedDot({
                index: 3
              })
            }
          })
        }
      }
    })
  },
  //去逛逛
  spellGoods() {
    wx.switchTab({
      url: '/pages/fenlei/fenlei'
    })
  },

  //获取数量
  inputNum(e) {
    let that = this
    if (e.detail.value == "" || e.detail.value == 0) {
      that.setData({
        inputNum: that.data.inputNum1
      })
    } else {
      that.setData({
        inputNum: e.detail.value
      })
    }

  },

  //获取焦点
  bindconfocus(e) {

    this.setData({
      inputNum1: e.currentTarget.dataset.item.amount,
      goodsName: e.currentTarget.dataset.item.goodsName,
      goodsDetailsId: e.currentTarget.dataset.item.goodsDetailsId,
      price: e.currentTarget.dataset.item.price,
      totalPrice1: e.currentTarget.dataset.item.totalPrice,
      //起送数量
      detailStartNum: e.currentTarget.dataset.item.detailStartNum,
      indexs: e.currentTarget.dataset.index
    })
  },
  //失去焦点
  bindconfirm(e) {
    var that = this;
    if (that.data.inputNum == "") {

    } else {
      if (Number(that.data.inputNum) >= Number(that.data.detailStartNum)) {
        let userInfoId = wx.getStorageSync("openId")
        let cityId = wx.getStorageSync("cityId")
        let goodsName = that.data.goodsName
        let goodsDetailsId = that.data.goodsDetailsId
        let price = that.data.detailPrice
        let amount = that.data.inputNum
        let totalPrice = that.data.totalPrice1
        let carts = that.data.list

        api.set_amount({
          cityId,
          userInfoId,
          goodsName,
          goodsDetailsId,
          amount,
          price,
          totalPrice
        }).then(res => {
          if (res.data > 0) {
            wx.setTabBarBadge({
              index: 3,
              text: res.data //显示的内容 
            })
          } else {
            wx.hideTabBarRedDot({
              index: 3
            })
          }

          if (res.result) {
            carts[that.data.indexs].amount = that.data.inputNum;
            // that.setData({
            //   list: carts
            // });
            that.uploadGoodsRecommend()
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none'
            })
            carts[that.data.indexs].amount = that.data.inputNum1;
            that.setData({
              list: carts
            });
          }
        })
      } else {
        if (that.data.inputNum != "") {
          wx.showToast({
            title: '请输入最小起送数量' + that.data.detailStartNum,
            icon: 'none'
          })
        }
      }
    }
  },


  bindconfirm1(e) {
    var that = this;
    if (that.data.inputNum == "") {

    } else {
      if (Number(that.data.inputNum) >= Number(that.data.detailStartNum)) {
        let userInfoId = wx.getStorageSync("openId")
        let cityId = wx.getStorageSync("cityId")
        let goodsName = that.data.goodsName
        let goodsDetailsId = that.data.goodsDetailsId
        let price = that.data.detailPrice
        let amount = that.data.inputNum
        let totalPrice = that.data.totalPrice1
        let carts = that.data.list
        api.set_amount({
          cityId,
          userInfoId,
          goodsName,
          goodsDetailsId,
          amount,
          price,
          totalPrice
        }).then(res => {
          if (res.data > 0) {
            wx.setTabBarBadge({
              index: 3,
              text: res.data //显示的内容 
            })
          } else {
            wx.hideTabBarRedDot({
              index: 3
            })
          }
          if (res.result) {
            carts[that.data.indexs].amount = that.data.inputNum;
            that.setData({
              list: carts
            });
            that.uploadGoodsRecommend()
          } else {
            wx.showToast({
              title: res.msg,
              icon: 'none'
            })
            carts[that.data.indexs].amount = that.data.inputNum1;
            that.setData({
              carts: carts
            });
          }

        })
      } else {
        if (that.data.inputNum != "") {
          wx.showToast({
            title: '请输入最小起送数量' + that.data.detailStartNum,
            icon: 'none'
          })
        }
      }
    }
  },
  toFenLei() {
    wx.switchTab({
      url: '/pages/fenlei/fenlei',
    })
  },
  toActivity(e) {
    const {
      goods
    } = this.data
    const {
      activityfullreduceid
    } = e.currentTarget.dataset
    const activityName = `满${goods[activityfullreduceid].fullAmount}减${goods[activityfullreduceid].mayReduce}`
    wx.navigateTo({
      url: '/pages/searchActivity/searchActivity?activityFullReduceId=' + activityfullreduceid + '&activityName=' + activityName,
    })
  }
})